const { sequelize, Region } = require('../models');
const { Op } = require('sequelize');

class RegionService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20) {
		const { name } = filter;

		const where = {};
		if (name) where['name'] = { [Op.like]: `%${name}%` };

		const provinces = [];
		const citys = [];
		const districts = [];

		if (Object.keys(where).length) {
			//获取所有符合条件的记录
			const data = await Region.findAll({
				where
			});

			if (!data.length) return {
				data: [],
				total: 0
			}

			/*
			provinces = Array.from(new Set(data.map((d) => d.parent_id === 0 ? d.id : parseInt(`${String(d.parent_id).slice(0, 2)}0000`))));
			citys = Array.from(new Set(data.map((d) => String(d.parent_id).slice(2, 4) === '00' ? d.id : parseInt(`${String(d.parent_id).slice(0, 4)}00`))));
			districts = Array.from(new Set(data.map((d) => String(d.parent_id).slice(4) === '00' ? d.id : 0)));
			*/

			data.forEach((d) => {
				if (d.parent_id === 0) {
					provinces.push(d.id);
				} else if (String(d.parent_id).slice(2, 4) === '00') {
					provinces.push(d.parent_id);
					citys.push(d.id);
				} else if (String(d.parent_id).slice(4) === '00') {
					provinces.push(parseInt(`${String(d.parent_id).slice(0, 2)}0000`));
					citys.push(parseInt(`${String(d.parent_id).slice(0, 4)}00`));
					districts.push(d.id);
				}
			})
		}

		/*
		const { count: total, rows: data } = await Region.findAndCountAll({
			attributes: ['id', 'name', 'level'],
			where: {
				parent_id: 0
			},
			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['sort', 'asc'],
				['id', 'asc']
			]
		});

		for (const i in data) {
			data[i].setDataValue('children', await data[i].getChildren());
		}
		*/

		const { count: total, rows } = await Region.findAndCountAll({
			attributes: ['id'],
			where: (() => {
				const where = { parent_id: 0 };
				if (provinces.length) where.id = { [Op.in]: provinces };

				return where;
			})(),

			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['sort', 'asc'],
				['id', 'asc']
			]
		});

		const data = await Region.findAll({
			attributes: ['id', 'name', 'level', 'sort', ['id', 'key']],
			where: {
				'id': { [Op.in]: rows.map((d) => d.id) }
			},
			include: {
				model: Region,
				as: 'children',
				attributes: ['id', 'name', 'level', 'sort', ['id', 'key']],

				where: (() => {
					const where = {};
					if (citys.length) where.id = { [Op.in]: citys };
					return where;
				})(),

				include: {
					model: Region,
					as: 'children',
					attributes: ['id', 'name', 'level', 'sort', ['id', 'key']],

					where: (() => {
						const where = {};
						if (districts.length) where.id = { [Op.in]: districts };
						return where;
					})(),

					required: false
				},

				required: false
			},
			order: [
				['sort', 'asc'],
				['id', 'asc']
			]
		})

		return {
			data,
			total
		}
	}

	async cascader(parent_id) {
		return Region.findAll({
			raw: false,
			attributes: [['id', 'value'], ['name', 'label']],
			where: {
				parent_id
			},
			include: {
				model: Region,
				as: 'children',
				attributes: [['id', 'value'], ['name', 'label']]
			},
			order: [
				['sort', 'asc'],
				['id', 'asc']
			]
		})
	}

	async save(params) {
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		const { id, parent_id } = params;
		if (!id) throw '地区编号必须为数字，且不能为空';

		const data = await Region.findByPk(id);
		if (data?.id) {
			return Region.update(params, {
				where: { id }
			})
		} else {
			if (parent_id === 0) {
				params.level = 1;
			} else {
				const parentData = await Region.findByPk(parent_id);
				params.level = parseInt(parentData.level) + 1;
			}

			return Region.create(params);
		}
	}
	async delete(id) {
		const data = await Region.findByPk(id);
		//删除当前记录
		Region.destroy({
			where: { id },
			force: true
		});
		//删除当前栏目的子栏目
		if (data.level === 2) {
			Region.destroy({
				where: {
					parent_id: id
				},
				force: true
			})
		} else if (data.level === 1) {
			Region.destroy({
				where: {
					parent_id: { [Op.startsWith]: String(id).slice(0, 2) }
				},
				force: true
			})
		}

		return true;
	}
}

exports = module.exports = RegionService;
